<?php
/**
 * @file imagelibrary.php $
 * @author LiangJian (liangjian@haibao.com) $
 * @date 2015年8月3日 上午10:45:47 $
 * @brief APP图片管理 $
 */
namespace haibao\app\business;

class ImageLibrary extends \haibao\app\business\Base{

    /**
     * @var $_instance
     */
    private static $_instance;
    
    /**
     * instance()
     */
    private static function instance(){
        if(!self::$_instance){
            self::$_instance = new \haibao\app\data\ImageLibrary();
        }
        return self::$_instance;
    }
    
    /**
     * 根据图片ID查询单张图片
     */
    public static function getImageById($imageId, $brief = false){
        return self::instance()->getImageById($imageId, $brief);
    }
    
    /**
     * 根据图片id查询多张图片
     */
    public static function getImageByIds(array $imageIds,$brief = false){
        if(!$imageIds){
            throw new BusinessException('图片ID传递错误');
        }
        return self::instance()->getImageByIds($imageIds,$brief);
    }
    
    /**
     * 根据图片id查询对应明星
     */
    public static function getStarByImageId($imageId){
        return self::instance()->getStarByImageId($imageId);
    }
    
    /**
     * 根据图片id查询对应品牌
     */
    public static function getBrandByImageId($imageId){
        return self::instance()->getBrandByImageId($imageId);
    }
    
    /**
     * 根据图片id查询对应服饰
     */
    public static function getFashionByImageId($imageId){
        return self::instance()->getFashionByImageId($imageId);
    }
    
    /**
     * 根据图片id查询对应地区
     */
    public static function getAreaByImageId($imageId){
        return self::instance()->getAreaByImageId($imageId);
    }
    
    /**
     * 筛选图片
     */
    public static function getImageLibraryByQuery($query){
        self::checkOperation(self::FUNC_CODE_APP_IMAGE_LIST);
        
        if(!$query){
            $query = new \haibao\app\model\filter\ImageLibrary();
        }
        
        return self::instance()->getImageLibraryByQuery($query);
    }
    
    /**
     * 保存图片详细信息
     * @param \haibao\app\model\data\ImageLibrary $model
     */
    public static function saveImageLibrary($model){
        self::checkOperation(self::FUNC_CODE_APP_IMAGE_UPDATE);
        self::checkForm($model);
        if(!$model->Id){
            throw new BusinessException('图片ID传递错误');
        }
        $model->Id = explode(',', $model->Id);
        if($model->ImageStar){
            $model->ImageStar = explode(',', $model->ImageStar);
        }
        if($model->ImageBrand){
            $model->ImageBrand = explode(',', $model->ImageBrand);
        }
        if($model->ImageFashion){
            $model->ImageFashion = explode(',', $model->ImageFashion);
        }
        if($model->ImageArea){
            $model->ImageArea = explode(',', $model->ImageArea);
        }
        if($model->ImageEvent){
        	$model->ImageEvent = explode(',', $model->ImageEvent);
        }
        $model->CreateBy = self::getCurrentUser()->Id;
        $model->CreateTime = new \DateTime();
        self::instance()->updateImageLibrary($model);
        
        self::saveOperateHistory(self::FUNC_CODE_APP_IMAGE_UPDATE, $model->toArray(true,true));
    }
    
    /**
     *表单验证 
     */
    private static function checkForm($model){
    	if($model->ImgType == 'product'){
    		if($model->ImageBrand == ''){
    			throw new BusinessException('品牌标签不能为空');
    		}
    		if($model->ProductName == ''){
    			throw new BusinessException('品名不能为空');
    		}
    		if($model->Price == ''){
    			$model->PriceType = null;
    		}
    	}
    	if($model->ImgType == 'star'){
    		if($model->Description == ''){
    			throw new BusinessException('图注不能为空');
    		}
    	}
    	
    }
    
    /**
     * 删除图片
     */
    public static function deleteImage($imageId){
        self::checkOperation(self::FUNC_CODE_APP_IMAGE_DELETE);
        self::instance()->updateImageStatus(array($imageId), \haibao\app\model\data\ImageLibrary::STATUS_DISABLE);
        self::saveOperateHistory(self::FUNC_CODE_APP_IMAGE_DELETE, array($imageId, \haibao\app\model\data\ImageLibrary::STATUS_DISABLE));
    }
    
    /**
     * 保存上传图片到库中
     * @param \haibao\cms\model\data\ImageLibrary $model
     */
    public static function saveUpload($file, $imageType=\haibao\app\model\data\ImageLibrary::IMAGE_TYPE_PERSON, $upSource=\haibao\app\model\data\ImageLibrary::UPLOAD_SOURCE_IMAGE_LIBRARY, $uploadBasePath){
        self::checkOperation(self::FUNC_CODE_APP_IMAGE_ADD);
        
        $storagePath = self::getUploadStoragePath($file['name'], $uploadBasePath);
        
        $userId = self::getCurrentUser()->Id;
        $userName = self::getCurrentUser()->UserName;
    
        list($width, $height) = getimagesize($file['tmp_name']);
        $picId = self::instance()->saveImage($width, $height, $storagePath, $imageType, $userId, $upSource);
        self::generateImage($storagePath, file_get_contents($file['tmp_name']));
    
        self::saveOperateHistory(self::FUNC_CODE_APP_IMAGE_ADD, $file);
    
        return array(
            'id' => $picId,
            'imageUrl' => $storagePath
        );
    }
    
    /**
     * 根据用户Id获取曾经收藏图片列表
     */
    public static function getCollectionById($userId,$currentPage = 1,$pageSize = 200){
    	if(!$userId){
    		throw new BusinessException('参数不正确',\haibao\app\business\Oauth::DATA_ERROR_CODE_EMPTY);
    	}
        return self::instance()->getCollectionById($userId,$currentPage,$pageSize);
    }
    
    public static function getUserHasCollection($userId){
    	if(!$userId){
    		throw new BusinessException('参数不正确',\haibao\app\business\Oauth::DATA_ERROR_CODE_EMPTY);
    	}
    	return self::instance()->getUserHasCollection($userId);
    }

    /**
     * 批量下载图片
     * @param int/array $imageIds
     * @throws BusinessException
     */
    public static function downloadImage($imageIds){
    	self::checkOperation(self::FUNC_CODE_IMAGE_LIBRARY_DOWNLOAD);
    
    	$models = self::getImagesById((array)$imageIds);
    	if(!$models){
    		throw new BusinessException('下载失败');
    	}
    	$saveFilename = \haibao\classlibrary\app\Config::getConfig(\haibao\classlibrary\app\Config::IMAGE_UPLOAD_BASE_PATH);
    	if(file_exists($saveFilename)){
    		chmod($saveFilename, 0777);
    		unlink($saveFilename);
    	}
    	$zip = new \ZipArchive();
    	$res = $zip->open($saveFilename, \ZIPARCHIVE::CREATE);
    
    	if ( $res === TRUE) {
    		foreach ($models as $model){
    			$filePath = self::getSaveImagePath($model->Filename);
    			if(file_exists($filePath)){
    				$zip->addFile($filePath, basename($filePath));
    			}
    		}
    		$zip->close();
    		self::saveOperateHistory(self::FUNC_CODE_IMAGE_LIBRARY_DOWNLOAD, $models);
    	}
    	return $saveFilename;
    }
    
    /**
     * @param int/array $id
     */
    public static function getImagesById($imageIds){
    	if(!$imageIds){
    		throw new BusinessException('图片ID传递错误');
    	}
    	$data = new \haibao\app\data\ImageLibrary();
    	return $data->getImageByIdDownLoad((array)$imageIds);
    }
    
    /**
     * 根据图片Id查询图片相关明星和地标信息
     * @param array $imageIdArr
     */
    public static function getImageProperty(array $imageIdArr){
        if(!$imageIdArr){
            throw new BusinessException('参数不正确', \haibao\app\business\Oauth::DATA_ERROR_CODE_EMPTY);
        }
        $imageIdArr = array_filter(array_unique($imageIdArr));
        return \haibao\app\business\ImageLibrary::getImageByIds($imageIdArr);
    }
    
    /**
     * 获取要上传文件的存储路径
     * @return string /upload/2014/1230/1419842617.9557.jpg
     */
    private static function getUploadStoragePath($orgionName, $uploadBasePath){
        $basePath = $uploadBasePath.date('Y') . DIRECTORY_SEPARATOR . date('md') . DIRECTORY_SEPARATOR . microtime(true);
        $extension = pathinfo($orgionName);
        $basePath .= '.' . strtolower($extension['extension']);
        return str_replace(array('/', '\\'), '/', $basePath);
    }

    /**
     * 保存生图片
     */
    private static function generateImage($path, $stream){
        $savePath = self::getSaveImagePath($path);
        self::createDir($savePath);
        file_put_contents($savePath, $stream, LOCK_EX);
    }
	
	/**
	 * 获取文件保存路径
	 */
	private static function getSaveImagePath($path){
		return \haibao\frame\Environment::path() . $path;
	}
	
	/**
	 * 创建文件保存路径
	 */
	private static function createDir($path){
		$path = pathinfo( $path );
		return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
	} 
	
	/**
	 * 获取cms图片信息 到APP库
	 */
	public static function addImageToApp($images,$typeFinal){
		$imageIds = array();
	    foreach($images as $key=>$val){
	        //$imageResult = self::instance()->getOneImageByFile($val->Filename);
	        //if($imageResult['Filename']){
	        $imageIds[] = $val->Id;
	        //}
	    }
		$cmsImageLibraryBusiness = new \haibao\cms\business\ImageLibrary();
		$images = $cmsImageLibraryBusiness::getImagesById($imageIds);

		foreach($images as $key=>$val){
			$val->UpSource = \haibao\app\model\data\ImageLibrary::UPLOAD_SOURCE_IMAGE_LIBRARY;
			$val->CreateBy = self::getCurrentUser()->Id;
			$val->CreateTime = new \DateTime();
			$val->Status = \haibao\app\model\data\ImageLibrary::STATUS_ENABLE;
		}
		self::instance()->addImageToApp($images,$typeFinal);
	}
	
	/**
	 * 保存单品库图片信息到APP商品库
	 */
	public static function addProductImageToApp($productInfo){
		foreach($productInfo as $key=>$val){
			$productInfo[$key]['UpSource'] = \haibao\app\model\data\ImageLibrary::UPLOAD_SOURCE_IMAGE_LIBRARY;
			$productInfo[$key]['CreateTime'] = new \DateTime();
			$productInfo[$key]['Status'] = \haibao\app\model\data\ImageLibrary::STATUS_ENABLE;
			$productInfo[$key]['CreateBy'] = self::getCurrentUser()->Id;
		}
		self::instance()->addProductImageToApp($productInfo);
	}
	
	public static function addPcImageToApp($imageArr){
	    if(!$imageArr){
	        return false;
	    }
	    $imageInfo = \haibao\cms\business\ImageLibrary::getImagesById($imageArr);
	    foreach($imageInfo as $key=>$val){
	        $imageInfo[$key]->CreateTime = new \DateTime();
	        $imageInfo[$key]->UpSource = \haibao\app\model\data\ImageLibrary::UPLOAD_SOURCE_IMAGE_LIBRARY;
	        $imageInfo[$key]->Status = \haibao\app\model\data\ImageLibrary::STATUS_ENABLE;
	        $imageInfo[$key]->CreateBy = self::getCurrentUser()->Id;
	    }
	    return array(self::instance()->addImageToApp($imageInfo,1),$imageInfo);
	}

}